<?php
namespace app\controller;

use think\Request;
use think\Response;
use think\facade\Db;
use app\BaseController;

class Init extends BaseController
{
    private $lockFile = '../init/database/init.lock';
    
    /**
     * 初始化数据库
     */
    public function initDatabase()
    {
        // 检查是否已经初始化
        if (file_exists($this->lockFile)) {
            return json([
                'status' => 400,
                'message' => '数据库已经初始化，如需重新初始化请先删除 database/init.lock 文件'
            ]);
        }

        try {
            // 先删除表
            Db::execute("DROP TABLE IF EXISTS `operation_logs`");
            Db::execute("DROP TABLE IF EXISTS `reminders`");
            Db::execute("DROP TABLE IF EXISTS `users`");
            
            // 创建表
            $this->createUsersTable();
            $this->createRemindersTable();
            $this->createOperationLogsTable();
            
            // 创建锁文件
            $this->createLockFile();
            
            return json([
                'status' => 200,
                'message' => '数据库初始化成功'
            ]);
            
        } catch (\Exception $e) {
            return json([
                'status' => 500,
                'message' => '数据库初始化失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 创建用户表
     */
    private function createUsersTable()
    {
        $sql = "CREATE TABLE `users` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(50) NOT NULL,
            `password` varchar(255) NOT NULL,
            `email` varchar(100) NOT NULL,
            `verification_token` varchar(255) DEFAULT NULL,
            `is_verified` tinyint(1) NOT NULL DEFAULT '0',
            `reminder_key` varchar(255) DEFAULT NULL,
            `created_at` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '注册时间',
            `updated_at` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '最后更新时间',
            `is_deleted` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '删除时间',
            PRIMARY KEY (`id`),
            UNIQUE KEY `username` (`username`),
            UNIQUE KEY `email` (`email`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表'";
        
        Db::execute($sql);
    }
    
    /**
     * 创建提醒事项表
     */
    private function createRemindersTable()
    {
        $sql = "CREATE TABLE `reminders` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `user_id` int(11) NOT NULL,
            `title` varchar(255) NOT NULL,
            `description` text,
            `due_date` int(11) unsigned DEFAULT NULL,
            `is_completed` tinyint(1) NOT NULL DEFAULT '0',
            `notes` text,
            `created_at` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
            `updated_at` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '最后更新时间',
            `is_deleted` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '删除时间',
            `is_disabled` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否禁用',
            PRIMARY KEY (`id`),
            KEY `idx_user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='提醒事项表'";
        
        Db::execute($sql);
    }

    /**
     * 创建操作日志表
     */
    private function createOperationLogsTable()
    {
        $sql = "CREATE TABLE `operation_logs` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `user_id` int(11) NOT NULL COMMENT '操作用户ID',
            `operation_type` varchar(50) NOT NULL COMMENT '操作类型',
            `operation_desc` varchar(255) NOT NULL COMMENT '操作描述',
            `operation_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '操作时间',
            `ip_address` varchar(50) DEFAULT NULL COMMENT 'IP地址',
            `user_agent` varchar(255) DEFAULT NULL COMMENT '用户代理',
            PRIMARY KEY (`id`),
            KEY `idx_user_id` (`user_id`),
            KEY `idx_operation_time` (`operation_time`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表'";
        
        Db::execute($sql);
    }
    
    /**
     * 创建锁文件
     */
    private function createLockFile()
    {
        // 确保目录存在
        if (!is_dir(dirname($this->lockFile))) {
            mkdir(dirname($this->lockFile), 0777, true);
        }
        
        // 创建锁文件，写入初始化时间
        file_put_contents(
            $this->lockFile, 
            'Database initialized at: ' . date('Y-m-d H:i:s')
        );
    }
    
    /**
     * 检查数据库初始化状态
     */
    public function checkInitStatus()
    {
        return json([
            'status' => 200,
            'initialized' => file_exists($this->lockFile),
            'init_time' => file_exists($this->lockFile) ? 
                file_get_contents($this->lockFile) : null
        ]);
    }
} 